﻿using Assets.Scripts.DL.ComponentScripts;
using Assets.Scripts.DL.Consts;
using Assets.Scripts.DL.Enemy.CommonEnemy;
using Assets.Scripts.DL.Mgrs;
using System;
using UnityEngine;

namespace Assets.Scripts.DL.Enemy.SpriderBoss {
	public class SpiderBossBarrageAtk : CommonState<SpiderBossController> {
		readonly Timer _timer;
		int _curBarrageCnt;
		public SpiderBossBarrageAtk(SpiderBossController controller, StateEnum stateName) : base(controller, stateName) {
			_timer = _controller.StateData.AtkCdRecoder[StateName];

			AddConditionToSelf(() => _timer.Elapsed > _controller.BarrageCd);
		}

		public override void Enter() {
			_controller.PlayAnim(StateEnum.Atk4);
			_controller.Velocity = Vector2.zero;
			_curBarrageCnt = 0;
			_controller.StateData.AtkOver = false;
		}

		public override void Exit() {
			_timer.Reset();
		}

		public override void Update() {
			if (_controller.IsAnimPlayAt(_controller.BarrageNormalTime) && _curBarrageCnt < _controller.BarrageTimes) {
				_curBarrageCnt++;
				SendBarrage();
				AudioManager.Play(_controller.StateAudio, AudioStr.Barrage);
				_controller.PlayAnim(StateEnum.Atk4);//不知道播放同一个动画会不会重置normalizetime
			}
			else if (_curBarrageCnt >= _controller.BarrageTimes) {
				_controller.StateData.AtkOver = true;
			}
		}

		void SendBarrage() {

			var angleStep = Mathf.PI / _controller.BarrageDirCnts;
			//方向
			//方向，发送一个，需要指定方向，位置
			for (int i = 0; i <= _controller.BarrageDirCnts; i++) {
				float curAngle = i * angleStep;
				//Debug.Log($"{curAngle}");
				Vector2 vdir = new(Mathf.Cos(curAngle), Mathf.Sin(curAngle));
				var v = vdir * _controller.BarrageSpeed;
				var ball = ObjectPool.Instance.GetObject(ObjPoolStr.BarrageBall);
				ball.transform.position = _controller.transform.position + new Vector3(0, _controller.BarrageYOffset) + (Vector3)vdir * _controller.BarrageDisFromCenter;
				ball.GetComponent<BarrageBall>().Velocity = v;
			}
		}
	}
}
